const express = require('express')
const bodyParser = require('body-parser')
const userRouter = require('./routes/utlis')
const goodsRouter = require('./routes/goods')
const cartRouter = require('./routes/cart')
const {writeLog} = require('./middleware/middleware')
const {writeFileerror} = require('./utlis/utlis')
const app = express()
app.listen(8080,()=>{
    console.log('后台服务器，http://localhost:8080')
})

app.use(express.static('userimg'))

// 全局写日志中间件
app.use(writeLog)

// 获取form表单数据中间件
app.use(bodyParser.urlencoded({extended:false}))

// 导入路由：用户，商品，购物车
app.use('/users',userRouter)
app.use('/goods',goodsRouter)
app.use('/cart',cartRouter)

app.get('/',(req,res)=>{
    res.redirect('index.html')
})
app.get('/index.html',(req,res)=>{
    res.render('index')
})

// 404处理中间件
app.use((req,res,next)=>{
    writeFileerror('404-路径不合法')
    res.json({
        errorCode:404,
        msg:'路径不合法！'
    })
    next()
})

// 异常处理中间件
app.use((err,req,res,next)=>{
    writeFileerror(err)
    res.json({
        errorCode:10,
        msg:'err错误'
    })
    next()
})